// WebSocket连接测试工具
export class WebSocketTester {
  constructor() {
    this.testResults = []
  }

  // 测试WebSocket连接
  async testWebSocketConnection(url) {
    return new Promise((resolve) => {
      const startTime = Date.now()
      const result = {
        url,
        success: false,
        error: null,
        responseTime: 0,
        status: 'testing'
      }

      try {
        console.log(`🔍 测试WebSocket连接: ${url}`)
        
        const ws = new WebSocket(url)
        
        // 设置超时
        const timeout = setTimeout(() => {
          ws.close()
          result.error = '连接超时 (5秒)'
          result.responseTime = Date.now() - startTime
          result.status = 'timeout'
          resolve(result)
        }, 5000)

        ws.onopen = () => {
          clearTimeout(timeout)
          result.success = true
          result.responseTime = Date.now() - startTime
          result.status = 'connected'
          console.log(`✅ WebSocket连接成功: ${url}`)
          ws.close()
          resolve(result)
        }

        ws.onerror = (error) => {
          clearTimeout(timeout)
          result.error = this.getErrorMessage(error)
          result.responseTime = Date.now() - startTime
          result.status = 'error'
          console.error(`❌ WebSocket连接失败: ${url}`, error)
          resolve(result)
        }

        ws.onclose = (event) => {
          clearTimeout(timeout)
          if (!result.success) {
            result.error = `连接关闭 (代码: ${event.code})`
            result.responseTime = Date.now() - startTime
            result.status = 'closed'
          }
          resolve(result)
        }

      } catch (error) {
        result.error = `创建WebSocket失败: ${error.message}`
        result.responseTime = Date.now() - startTime
        result.status = 'exception'
        resolve(result)
      }
    })
  }

  // 获取错误信息
  getErrorMessage(error) {
    if (error.type === 'error') {
      return '网络连接失败 - 可能是服务器未启动或端口不可用'
    }
    return error.message || '未知错误'
  }

  // 测试HTTP连接
  async testHttpConnection(url) {
    try {
      const httpUrl = url.replace('ws://', 'http://').replace('wss://', 'https://')
      console.log(`🔍 测试HTTP连接: ${httpUrl}`)
      
      const response = await fetch(httpUrl, {
        method: 'GET',
        mode: 'no-cors', // 避免CORS问题
        timeout: 5000
      })
      
      return {
        success: true,
        status: 'http_available',
        message: 'HTTP服务可用'
      }
    } catch (error) {
      return {
        success: false,
        status: 'http_error',
        message: `HTTP连接失败: ${error.message}`
      }
    }
  }

  // 综合测试
  async runDiagnostics(baseUrl = 'http://127.0.0.1:8891') {
    console.log('🚀 开始WebSocket诊断...')
    
    const results = {
      baseUrl,
      tests: [],
      summary: {
        total: 0,
        passed: 0,
        failed: 0
      }
    }

    // 测试1: HTTP连接
    console.log('📡 测试1: HTTP连接')
    const httpTest = await this.testHttpConnection(baseUrl)
    results.tests.push({
      name: 'HTTP连接测试',
      ...httpTest
    })

    // 测试2: WebSocket连接 (原始URL)
    console.log('🔌 测试2: WebSocket连接')
    const wsUrl = baseUrl.replace('http', 'ws') + '/ws/alerts'
    const wsTest = await this.testWebSocketConnection(wsUrl)
    results.tests.push({
      name: 'WebSocket连接测试',
      ...wsTest
    })

    // 测试3: 其他可能的WebSocket端点
    const alternativeEndpoints = [
      '/ws',
      '/websocket',
      '/socket.io',
      '/ws/water-quality'
    ]

    for (const endpoint of alternativeEndpoints) {
      console.log(`🔌 测试3: 替代端点 ${endpoint}`)
      const altUrl = baseUrl.replace('http', 'ws') + endpoint
      const altTest = await this.testWebSocketConnection(altUrl)
      results.tests.push({
        name: `替代端点测试: ${endpoint}`,
        ...altTest
      })
    }

    // 统计结果
    results.tests.forEach(test => {
      results.summary.total++
      if (test.success) {
        results.summary.passed++
      } else {
        results.summary.failed++
      }
    })

    console.log('📊 诊断结果:', results)
    return results
  }

  // 生成诊断报告
  generateReport(results) {
    const report = []
    
    report.push('🔍 WebSocket连接诊断报告')
    report.push('=' .repeat(50))
    report.push(`基础URL: ${results.baseUrl}`)
    report.push(`测试时间: ${new Date().toLocaleString()}`)
    report.push('')
    
    report.push('📊 测试结果汇总:')
    report.push(`  总测试数: ${results.summary.total}`)
    report.push(`  成功: ${results.summary.passed}`)
    report.push(`  失败: ${results.summary.failed}`)
    report.push('')
    
    report.push('📋 详细测试结果:')
    results.tests.forEach((test, index) => {
      report.push(`${index + 1}. ${test.name}`)
      report.push(`   状态: ${test.success ? '✅ 成功' : '❌ 失败'}`)
      if (test.error) {
        report.push(`   错误: ${test.error}`)
      }
      if (test.responseTime) {
        report.push(`   响应时间: ${test.responseTime}ms`)
      }
      report.push('')
    })
    
    // 建议
    report.push('💡 建议:')
    if (results.summary.failed === results.summary.total) {
      report.push('   - 检查后端服务是否启动')
      report.push('   - 确认端口8891是否被占用')
      report.push('   - 检查防火墙设置')
      report.push('   - 确认WebSocket端点路径是否正确')
    } else if (results.summary.passed > 0) {
      report.push('   - 部分连接成功，检查WebSocket端点路径')
      report.push('   - 确认WebSocket协议支持')
    }
    
    return report.join('\n')
  }
}

// 创建全局实例
export const wsTester = new WebSocketTester()
